package com.north.light.libpython;

import android.content.Context;

import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;

import java.io.Serializable;

/**
 * author:li
 * date:2022/8/30
 * desc:python管理工具类
 */
public class PythonManager implements Serializable {
    private Context mContext;
    //是否已经初始化
    private boolean isInit  = false;


    private static class SingleHolder implements Serializable {
        static PythonManager mInstance = new PythonManager();
    }

    public static PythonManager getInstance() {
        return SingleHolder.mInstance;
    }

    private boolean checkInit() throws Exception{
        if(!isInit){
            throw new Exception("python sdk is not init");
        }
        return true;
    }


    /**
     * 初始化
     */
    public void init(Context context) {
        this.mContext = context.getApplicationContext();
        if (!Python.isStarted()) {
            Python.start(new AndroidPlatform(this.mContext));
            isInit = true;
        }
    }


    /**
     * 获取python对象
     */
    public PyObject getPythonObj(String fileName)  throws Exception{
        checkInit();
        Python py = Python.getInstance();
        return py.getModule(fileName);
    }

    /**
     * 执行某个文件里面的函数
     */
    public PyObject getPythonFunRes(String fileName, String funcName, Object... arg)  throws Exception{
        checkInit();
        PyObject backend = PythonManager.getInstance().getPythonObj(fileName);
        return backend.callAttr(funcName, arg);
    }

}
